//
//  QDTicketDetailViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/2.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit
import HandyJSON

typealias QDTicketDetailFooterView = QDPayTypeFooterView

/// 地铁乘车票详情
final class QDTicketDetailViewController: NWTableViewController,QDLargeTitleTableHeaderScrollable {

    /// 订单号
    var orderNum: String = "00201903092008525938"
    
    /// 导航rightItem
    lazy private var rightButtonItem: UIBarButtonItem = {
        
        let button = UIButton()
        button.setTitle("退票", for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.setTitleColor(/*QDColors.separator*/QDColors.theme, for: .normal)
        button.titleLabel?.font = Font.regular.font(size: 14)
        button.addTarget(self, action: #selector(rightButtonDidTap), for: .touchUpInside)
        
        self.button = button
        return UIBarButtonItem(customView: button)
    }()
    
    /// 支付类型选择视图
    lazy private var payTypeView: QDPayTypePickerView = {
        
        let pickerView = QDPayTypePickerView()
        pickerView.typeDelegate = self
        return pickerView
    }()
    
    /// 引用rightItem
    private weak var button: UIButton?
    /// 温馨提示的footer
    private let footerView = QDTicketDetailFooterView()
    /// 底部的视图
    private let bottomView = UIView()
    /// 底部的按钮
    private let bottomButton = UIButton()
    
    /// 票卡信息
    private var ticket = QDTicket()
    /// 大标题
    var largeTableHeaderView = QDLargeButtonTableHeaderView()
    
    
    convenience init(orderNum: String = "") {
        self.init()
        self.orderNum = orderNum
    }
    
    
    override func loadPropertysAtInitialization() {
        super.loadPropertysAtInitialization()
        
        headerRefreshEnable = false
        footerRefreshEnable = false
    }
    
    
    override func registerTableViewCellsAndReusableView() {
        tableView.register(QDRecordMetroTableCell.self, forCellReuseIdentifier: "ticket")
        tableView.register(QDOrderInfoTableViewCell.self, forCellReuseIdentifier: "info")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        // Header
        largeTableHeaderView.title = "车票详情"
        largeTableHeaderView.buttonTitle = "我想退票"
        largeTableHeaderView.button.isHidden = true
        largeTableHeaderView.backgroundColor = RecordBackgroundColor
        
        largeTableHeaderView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 0))
        largeTableHeaderView.ritl_height = QDLargeTitleTableHeaderViewNormalHeight + 8
        largeTableHeaderView.button.addTarget(self, action: #selector(rightButtonDidTap), for: .touchUpInside)
        
        tableView.tableHeaderView = largeTableHeaderView
        
        // Footer
        footerView.subtitleLabel1.text = "1.请至购票起始站扫码取票，取票站当日进站有效。"
        footerView.subtitleLabel2.text = "2.扫码取票仅一次使用有效，逾期未取票自动退款。"
        footerView.frame = CGRect(origin: .zero, size: CGSize(width: ritl_width, height: 0))
        footerView.ritl_height = footerView.height
        tableView.tableFooterView = footerView
        
        // BottomView
        bottomView.backgroundColor = .white
        
        bottomButton.titleLabel?.font = Font.regular.font(size: 18)
        bottomButton.titleLabel?.textAlignment = .center
        bottomButton.setTitle("扫码取票", for: .normal)
        bottomButton.setTitleColor(.white, for: .normal)
        bottomButton.backgroundColor = QDColors.theme
        bottomButton.addTarget(self, action: #selector(bottomButtonDidTap), for: .touchUpInside)

        view.addSubview(bottomView)
        bottomView.addSubview(bottomButton)
        
        //进行frame布局
        bottomView.ritl_size = CGSize(width: ritl_width, height: BarDistance.TabBar.height)
        bottomView.ritl_originX = 0
        bottomView.ritl_originY = ritl_height

        bottomButton.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview()
            make.height.equalTo(BarDistance.TabBar.normalHeight)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        //预先加载 rightItem
        navigationItem.rightBarButtonItem = self.rightButtonItem
        navigationItem.rightBarButtonItem = nil
        
        //
        requestOrderDetail()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //更新状态栏
        setNeedsStatusBarAppearanceUpdate()
    }
    
    
    override func makeTableViewConstraints() {}
    override var tableViewBackgroundColor: UIColor { return RecordBackgroundColor }
    
    // MARK: NavigationBar
    override var nav_mutableBarShadowHidden: Bool { return true }
    override var nav_barTintColor: UIColor { return RecordBackgroundColor }
    

    // MARK: @objc
    
    /// 右侧按钮点击的操作
    @objc func rightButtonDidTap(){
        
        //TODO: 如果是退票
        if ticket.state == .unTakeout {
            //退票
            requestRefund(); return
        }
        
        else if ticket.state == .refund {
            //重新购买
            print("重新购买")
            let ticketController = QDMetroTicketViewController()
            ticketController.type = .fromTicket
            //设置进出站
            ticketController.startStation = QDMetroSimpleStation(id: ticket.entryStationCode, name: ticket.entryStation)
            ticketController.endStation = QDMetroSimpleStation(id: ticket.exitStationCode, name: ticket.exitStation)
            
            //支付回调
            ticketController.resultHandler = { [unowned self] (orderId) in
                self.orderNum = orderId
                self.requestOrderDetail()//重新刷新
                self.sendTicketStatusDidChangedNotification(isDelay: false)
            }
            
            ritl_topNavigationPush(ticketController, animated: true)
        }
    }
    
    /// 底部的按钮点击
    @objc func bottomButtonDidTap(){
        
        //TODO: 确认支付
        if ticket.state == .unPay {
            payTypeView.show()
        }
        
        //TODO: 扫码取票
        else if (ticket.state == .unTakeout) {
            /// 弹出扫码
            QDScannerTicketViewController.presentScannerLoginViewController(from: self, orderId: ticket.orderNo) { [unowned self] in
//                self.requestOrderDetail()
                self.sendTicketStatusDidChangedNotification()
                self.navigationController?.popViewController(animated: false)
            }
        }
    }
    
    
    //MARK: UIScrollView
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        tableViewDidScroll(contentOfset: scrollView.contentOffset) { (isShow) in
            setNavigationBarShadowViewHidden(!isShow)
            
            if !largeTableHeaderView.button.isHidden {//如果存在按钮
                 navigationItem.rightBarButtonItem = isShow ? self.rightButtonItem : nil
            }
        }
    }
}


extension QDTicketDetailViewController: QDPayTypePickerViewDelegate {
    
    
    /// 选择后的回调
    func payTypePickerView(view: QDPayTypePickerView, select type: QDPayType) {
        
        //消失
        view.dismissAnimated()
        
        //获得订单号
        let orderNum = ticket.orderNo
        
        view.showTextHUD(text: "请求支付数据中..")
        
        //请求支付
        QDNetworkingManager.request(url: QDTicketHostUrl + "/self/ticketPayment", paramteres: ["orderNo": orderNum,"payChannel": type.rawValue], success: { (msg, data) in
            
            guard let paymentInfo = data["paymentInfo"] as? String else {
                view.showTextHUD(text: "支付数据错误.."); return
            }
            
            view.showTextHUD(text: "正在唤起支付渠道")
            
            // 开始支付
            QDPaymentManager.sharedInstance.pay(type: type, data: paymentInfo, orderId: self.ticket.orderNo, delegate: self, viewController: self)
            
        }) { (msg, errorType) in
            view.showTextHUD(text: msg)
        }
    }
    
    
    
    /// 请求退款
    private func requestRefund(){
        
        view.showTextHUD(text: "正在申请退款")
        
        QDNetworkingManager.request(url: QDCustomerHostUrl + "/onlineTicket/refund", paramteres: ["orderNum": ticket.orderNo], success: { (msg, data) in
            
            guard let ticketState = data["ticketState"] as? String else {
                self.view.showTextHUD(text: "返回退票状态不正确!"); return
            }
            
            if ticketState == "4" {//申请成功
                self.requestOrderDetail()//请求详情
            }
            
            //发送通知
            self.sendTicketStatusDidChangedNotification()
            
        }) { (msg, errorType) in
            self.view.showTextHUD(text: msg)
        }
    }
    
    
    /// 延时1s发送刷新通知
    private func sendTicketStatusDidChangedNotification(isDelay: Bool = true){
        
        if !isDelay {
            NotificationCenter.default.post(name: QDTicketStatusDidChangedNotificationName, object: nil); return
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            // 发送通知
            NotificationCenter.default.post(name: QDTicketStatusDidChangedNotificationName, object: nil)
        }
    }
    
}


extension QDTicketDetailViewController: QDPaymentManagerDelegate {
    
    func complete(orderId: String){
        view.showTextHUD(text: "支付成功")
        //避免重复
        bottomButton.isEnabled = false
        // 重置数据
        requestOrderDetail()
        //发送通知
        sendTicketStatusDidChangedNotification()
    }
    
    
    func fail(error: String,orderId: String) {
        view.showTextHUD(text: error)
    }
}



extension QDTicketDetailViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: indexPath.section == 0 ? "ticket" : "info", for: indexPath)
        
        if let ticketCell = cell as? QDRecordMetroTableCell {
            
            ticketCell.titleLabel.text = "车票信息"
            ticketCell.fillLabel.isHidden = true
            
            ticketCell.startLabel.text = ticket.entryStation
            ticketCell.endLabel.text = ticket.exitStation
            
            ticketCell.priceLabel.text = "\(NSNumber(value: ((Double(ticket.ticketAmount) ?? 0.0) / 100.0)))"
            ticketCell.descTimeLabel.text = "取票车站: \(ticket.entryStation)"
            ticketCell.timeLabel.text = ticket.stateDesc
        }
        
        else if let infoCell = cell as? QDOrderInfoTableViewCell {
            
            infoCell.titleLabel.text = "相关信息"
            
            infoCell.titles = ["订单编号：","支付方式：","车票单价：","车票数量：","下单时间：",ticket.stateTitleDesc]
            
            infoCell.subtitles = ["\(ticket.orderNo)",
                "\(ticket.payType.title)",
                "\(NSNumber(value: ((Double(ticket.price) ?? 0.0) / 100.0)))元",
                "\(ticket.ticketCount)张",
                "\(ticket.ticketTime)",
                "\(ticket.statusTime)"]
            
            infoCell.reload()
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return indexPath.section == 0 ? 154 : QDOrderInfoTableViewCell.height(count: 6)
    }
    
    
    /// 占位headerView
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = RecordBackgroundColor
        return view
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 10 : 6
    }
}


extension QDTicketDetailViewController {
    
    /// 请求订单详情
    private func requestOrderDetail(){
        
        view.showWatingHUD()
        
        QDNetworkingManager.request(url: QDCustomerHostUrl + "/onlineTicket/orderDetail", paramteres: ["orderNum":orderNum], success: { (msg, data) in
            
            self.view.dismissHUD()
            
            //开始解析
            guard let container = QDTicket.deserialize(from: data) else {
                self.view.showTextHUD(text: "数据结构错误"); return
            }
        
            self.ticket = container//赋值更新界面
            self.update()//刷新界面
            
        }) { (msg, errorType) in
            
            self.view.showTextHUD(text: msg)
        }
    }

    
    /// 更新界面
    private func update(){
        
        //刷新列表
        tableView.reloadData()
        //状态
        let state = ticket.state
        //设置颜色
        largeTableHeaderView.button.setTitleColor(QDColors.theme, for: .normal)
        //更新header
        largeTableHeaderView.button.isHidden = !(state == .unTakeout || state == .refund)
        //更新button
        largeTableHeaderView.button.setTitle(state.buttonName, for: .normal)
        //更新right
        button?.setTitle(largeTableHeaderView.button.title(for: .normal), for: .normal)
        //底部更新
        bottomView.ritl_originY = (state == .unTakeout || state == .unPay) ? ritl_height - bottomView.ritl_height : ritl_height
        //底部文字更新
        bottomButton.setTitle(state.bottomViewName, for: .normal)
    }
}

